<?php
namespace Api\Controller;

class SmsController extends APIController{	

    /*待验证的参数*/
    public $tca = [
        'phone' => [
            'method'    => 'regex',
            'model'     => '/^1[3|4|5|7|8|9]\d{9}$/',
            'code_key'  => 'phone_failed'
        ],
    ];

    /**
     * 发送验证码
     * @param  int  phone  手机号
     */
    public function sendSMSCode(){
        try{
            $this->safeChecked();
            $phone = I('param.phone');
            /*参数验证*/
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $userObj = D('Base');
            
            //验证码发送间隔时间验证
            $codeTime = $userObj->vilidateSendCode($phone);
            if(!$codeTime){
                $this->res_data['code_key'] = 'sms_code_wait';
                $this->apiReply();
            }

            //生成验证码
            $data_code = $userObj->createCode();
            //获取过期时间
            $expire = C('SMS_EXPIRED_TIME')/60;
            //发送验证码
            vendor('Aliyun.DySDKLite.Sms.sendSms');
            $key = 'LTAIIJwUUxRhkZD7';
            $secret = 'Uz9aAl6BeSPn1Ne3lflNJUD3W8mhX4';
            //验证码
            $param = [
                'PhoneNumbers' => $phone,
                'SignName' => '拼好菜',
                'TemplateCode' => 'SMS_155830022',
                'TemplateParam' => [
                    'code' => $data_code['code']
                ]
            ];
            $sms = new \Aliyun\DySDKLite\Sms\sendSms($key,$secret,$param);
            $result = $sms->send();
            if($result->Code != 'OK'){
                debug(json_encode($result,true));
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            //将生成的验证码放在缓存中
            $userObj->createCodeCache($phone,$data_code['code']);
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }
}